<template>
  <div class="app-container">
    <div class="top-container">
      <div class="search-container">
        <!-- 搜索框 -->
        <el-input
          v-model="searchQuery"
          placeholder="搜索申请人/项目名称/状态"
          class="filter-item"
          prefix-icon="el-icon-search"
          clearable
          @input="handleSearch"
        />
      </div>

      <!-- PDF文件链接显示区域 -->
      <div v-if="currentPdfFile" class="pdf-link-container">
        <span class="pdf-label">当前比对方案：</span>
        <a :href="currentPdfFile.url" target="_blank" class="pdf-link">
          {{ currentPdfFile.name }}
        </a>
        <el-button
          type="text"
          icon="el-icon-delete"
          class="delete-pdf"
          @click="handleDeletePdf"
        >
          删除
        </el-button>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <div class="table-header">
        <h2 class="table-title">比对测试申请表</h2>
        <el-button type="success" icon="el-icon-download" @click="exportExcel">
          导出比对测试单
        </el-button>
      </div>
      <el-table
        :data="
          filteredComparisonData.slice(
            (currentPage - 1) * pageSize,
            currentPage * pageSize
          )
        "
        style="width: 100%"
        border
      >
        <el-table-column prop="cpId" label="序号" width="80" />
        <el-table-column prop="uRealName" label="比对测试申请人" />
        <el-table-column prop="pjName" label="项目名称" />
        <el-table-column prop="startDate" label="计划时间" />
        <el-table-column prop="endDate" label="完成时间">
          <template slot-scope="scope">
            <span>{{
              scope.row.endDate === "" ? "-" : scope.row.endDate
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="cpStatus" label="状态">
          <template slot-scope="scope">
            <span :style="{ color: getStatusColor(scope.row.cpStatus) }">
              {{ getStatusText(scope.row.cpStatus) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="handleComparisonEdit(scope.row)"
            >
              修改
            </el-button>
            <el-button
              type="text"
              size="small"
              style="color: #f56c6c"
              @click="handleComparisonDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredComparisonData.length"
        >
        </el-pagination>
      </div>
    </div>

    <!-- 修改状态弹窗 - 移动到这里 -->
    <el-dialog title="修改状态" :visible.sync="editDialogVisible" width="30%">
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="状态">
          <el-select v-model="editForm.status" placeholder="请选择状态">
            <el-option label="计划中" :value="0" />
            <el-option label="已完成" :value="1" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEdit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as XLSX from "xlsx";

export default {
  data() {
    return {
      searchQuery: "",
      currentPage: 1,
      pageSize: 10,
      currentPdfFile: null,
      comparisonDialogVisible: false,
      comparisonData: [],
      comparisonForm: {
        applicant: "",
        projectName: "",
        planTime: "",
        completionTime: "",
        status: "",
      },
      filterForm: {
        comparisonFilter: {
          applicant: "",
          projectName: "",
          status: "",
          dateRange: [],
        },
      },
      statusOptions: [
        { label: "全部", value: "" },
        { label: "计划中", value: "计划中" },
        { label: "已完成", value: "已完成" },
      ],
      uploadUrl:  "http://localhost:8081/upload/document",
      headers: {
        Authorization: "Bearer " + this.$store.state.user.token,
      },
      currentId: null,
      comparisonRules: {
        applicant: [
          { required: true, message: "请输入申请人", trigger: "blur" },
        ],
        projectName: [
          { required: true, message: "请输入项目名称", trigger: "blur" },
        ],
        planTime: [
          { required: true, message: "请选择计划时间", trigger: "change" },
        ],
        status: [{ required: true, message: "请选择状态", trigger: "change" }],
      },
      editDialogVisible: false,
      editForm: {
        id: null,
        status: null
      }
    };
  },
  computed: {
    filteredComparisonData() {
      let result = this.comparisonData || [];

      // 搜索查询
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase();
        result = result.filter(
          (item) =>
            (item.uRealName && String(item.uRealName).toLowerCase().includes(query)) ||
            (item.pjName && String(item.pjName).toLowerCase().includes(query)) ||
            (this.getStatusText(item.cpStatus).toLowerCase().includes(query))
        );
      }

      return result;
    },
  },
  created() {
    this.fetchComparisonData();
  },
  methods: {
    fetchComparisonData() {
      this.$http
        .get("/comparison/list")
        .then((response) => {
          console.log('原始响应数据:', response.data);
          if (!response.data) {
            console.warn('返回数据为空');
            this.comparisonData = [];
            return;
          }
          // 检查每条数据的字段
          this.comparisonData = response.data.map(item => {
            console.log('处理前的单条数据:', item);
            // 检查 uRealName 是否存在
            if (!item.uRealName) {
              console.warn('uRealName 为空:', item);
            }
            return {
              ...item,
              cpId: item.cpId,
              uRealName: item.uRealName || '未知用户',  // 添加默认值
              pjName: item.pjName || '未知项目',
              startDate: item.startDate,
              endDate: item.endDate,
              cpStatus: item.cpStatus
            };
          });
          console.log('处理后的数据:', this.comparisonData);
        })
        .catch((error) => {
          console.error("获取对比测试数据失败:", error);
          console.error("错误详情:", error.response?.data);
          this.$message.error("获取对比测试数据失败：" + (error.response?.data?.message || error.message));
        });
    },

    handleSearch() {
      this.currentPage = 1;
    },

    handleComparisonUploadSuccess(response) {
      this.currentPdfFile = {
        name: response.fileName || "比对方案.pdf",
        url: response.url,
      };
      this.$message.success("比对方案上传成功");
    },

    handleUploadError(error) {
      this.$message.error("文件上传失败：" + error.message);
    },

    beforeUpload(file) {
      const isPdf = file.type === "application/pdf";
      if (!isPdf) {
        this.$message.error("只能上传 PDF 文件!");
        return false;
      }
      const isLt20M = file.size / 1024 / 1024 < 20;
      if (!isLt20M) {
        this.$message.error("文件大小不能超过 20MB!");
        return false;
      }
      return true;
    },

    showComparisonDialog() {
      if (!this.currentPdfFile) {
        this.$message.warning("请先上传比对方案文件");
        return;
      }
      this.comparisonDialogVisible = true;
    },

    handleUpdateSuccess(response) {
      this.currentPdfFile = {
        name: response.fileName || "比对方案.pdf",
        url: response.url
      };
      this.$message.success("比对方案更新成功");
      this.comparisonDialogVisible = false;

      this.updateComparisonFile({
        fileUrl: response.url,
        fileName: response.fileName
      });
    },

    async updateComparisonFile(fileInfo) {
      try {
        await this.$http.put('/comparison/update-file', {
          fileUrl: fileInfo.fileUrl,
          fileName: fileInfo.fileName
        });
        this.fetchComparisonData();
      } catch (error) {
        console.error('更新文件记录失败:', error);
        this.$message.error('更新文件记录失败');
      }
    },

    handleComparisonEdit(row) {
      console.log('编辑行原始数据:', row);
      this.editForm = {
        id: Number(row.cpId),
        status: Number(row.cpStatus)  // 临时存储在 status 中
      };
      console.log('编辑表单数据:', this.editForm);
      this.editDialogVisible = true;
    },

    handleComparisonDelete(row) {
      this.$confirm("确认删除该比对方案吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http
            .delete(`/comparison/deleteComparison/${row.cpId}`)
            .then(() => {
              this.$message.success("删除成功");
              this.fetchComparisonData();
            })
            .catch((error) => {
              this.$message.error("删除失败：" + error.message);
            });
        })
        .catch(() => {});
    },

    handleDeletePdf() {
      this.$confirm("确认删除当前比对方案吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.currentPdfFile = null;
          this.$message.success("删除成功");
        })
        .catch(() => {});
    },

    exportExcel() {
      const data = this.filteredComparisonData.map((item) => ({
        序号: item.cpId,
        比对测试申请人: item.uRealName,  // 改为使用 uRealName
        项目名称: item.pjName,
        计划时间: item.startDate,
        完成时间: item.endDate || "-",
        状态: this.getStatusText(item.cpStatus)
      }));

      const ws = XLSX.utils.json_to_sheet(data);
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, "比对测试单");
      XLSX.writeFile(wb, "比对测试单.xlsx");
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
    },

    handleCurrentChange(val) {
      this.currentPage = val;
    },

    handleFilter() {
      this.currentPage = 1;
      const filter = this.filterForm.comparisonFilter;
      
      // 构建查询参数
      const params = {
        startDate: filter.dateRange?.[0],
        endDate: filter.dateRange?.[1]
      };

      // 调用后端API进行筛选
      this.$http.get('/comparison/list', { params })
        .then(response => {
          this.comparisonData = response.data;
        })
        .catch(error => {
          console.error('筛选数据失败:', error);
          this.$message.error('筛选数据失败：' + error.message);
        });
    },

    resetFilter() {
      this.searchQuery = '';
      this.filterForm.comparisonFilter.dateRange = [];
      this.fetchComparisonData();
    },

    getStatusColor(status) {
      // 确保使用数字比较
      const statusNum = Number(status);
      return statusNum === 0 ? "#E6A23C" : "#67C23A";
    },

    getStatusText(status) {
      // 确保使用数字比较
      const statusNum = Number(status);
      return statusNum === 0 ? "计划中" : "已完成";
    },

    async submitEdit() {
      try {
        // 只发送 cpStatus 字段
        const updateData = {
          cpStatus: Number(this.editForm.status)
        };
        console.log('发送更新请求:', {
          url: `/comparison/updateComparison/${this.editForm.id}`,
          data: updateData
        });
        
        const response = await this.$http.put(
          `/comparison/updateComparison/${this.editForm.id}`, 
          updateData
        );
        
        console.log('更新响应:', response);
        
        if (response.data !== undefined) {
          this.$message.success('修改成功');
          this.editDialogVisible = false;
          await this.fetchComparisonData();
        } else {
          throw new Error('更新失败：服务器未返回数据');
        }
      } catch (error) {
        console.error('修改失败:', error);
        console.error('错误详情:', error.response?.data);
        this.$message.error('修改失败：' + (error.response?.data?.message || error.message));
      }
    },
  },
};
</script>
  <style scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.top-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.table-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pdf-link-container {
  margin: 15px 0;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
  display: flex;
  align-items: center;
}

.pdf-label {
  color: #606266;
  margin-right: 10px;
}

.pdf-link {
  color: #409eff;
  text-decoration: none;
  margin-right: 15px;
}

.pdf-link:hover {
  text-decoration: underline;
}

.delete-pdf {
  color: #f56c6c;
}

.delete-pdf:hover {
  color: #f78989;
}

.filter-form {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.filter-form-inline {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.filter-form-inline .el-form-item {
  margin-bottom: 0;
  margin-right: 10px;
}

.filter-form-inline .el-input {
  width: 200px;
}

.filter-form-inline .el-date-editor {
  width: 320px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 表格样式优化 */
.el-table {
  margin-top: 20px;
}

.el-table th {
  background-color: #f5f7fa;
  color: #606266;
}

.el-table .el-button {
  padding: 0 8px;
}

/* 搜索框样式 */
.filter-item .el-input__inner {
  border-radius: 20px;
}

/* 弹窗表单样式 */
.el-dialog .el-form-item {
  margin-bottom: 20px;
}

.el-dialog .el-date-editor {
  width: 100%;
}

.el-dialog .dialog-footer {
  text-align: right;
}

/* 按钮样式优化 */
.el-button.el-button--text {
  padding: 0 8px;
}

.el-button.el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
}

.el-button.el-button--primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.el-button.el-button--warning {
  background-color: #e6a23c;
  border-color: #e6a23c;
}

.el-button.el-button--warning:hover {
  background-color: #ebb563;
  border-color: #ebb563;
}

.el-button.el-button--success {
  background-color: #67c23a;
  border-color: #67c23a;
}

.el-button.el-button--success:hover {
  background-color: #85ce61;
  border-color: #85ce61;
}

/* 响应式布局调整 */
@media screen and (max-width: 768px) {
  .filter-form-inline .el-form-item {
    margin-right: 0;
    width: 100%;
  }

  .filter-form-inline .el-input,
  .filter-form-inline .el-date-editor {
    width: 100%;
  }

  .action-buttons {
    flex-direction: column;
    gap: 10px;
    width: 100%;
    max-width: 300px;
    margin: 0 auto;
  }

  .action-buttons .el-button {
    width: 100%;
  }
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.table-title {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.search-container {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.filter-item {
  width: 300px !important;
}

.filter-item .el-input__inner {
  border-radius: 20px;
  height: 40px;
  line-height: 40px;
}

/* 移动端适配 */
@media screen and (max-width: 768px) {
  .filter-item {
    width: 100% !important;
  }
}

/* PDF文件链接区域样式保持不变 */
.pdf-link-container {
  margin: 15px 0;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
  display: flex;
  align-items: center;
}

/* 响应式布局调整 */
@media screen and (max-width: 768px) {
  .search-container {
    flex-direction: column;
    align-items: stretch;
  }

  .filter-item {
    width: 100% !important;
  }

  .table-header {
    flex-direction: column;
    gap: 10px;
  }

  .table-title {
    margin-bottom: 10px;
  }
}
</style>

<style lang="scss" scoped>
.upload-container {
  padding: 20px;
  text-align: center;
}

.upload-area {
  :deep(.el-upload-dragger) {
    width: 360px;
    height: 180px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    
    &:hover {
      border-color: #409EFF;
    }
  }
}

.el-upload__text {
  margin: 10px 0;
  font-size: 14px;
  color: #606266;

  em {
    color: #409EFF;
    font-style: normal;
  }
}

.el-upload__tip {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
}
</style>

